package com.youxin.admin.basic.context;

import com.youxin.utils.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class FileContext {

    private static Logger logger = LoggerFactory.getLogger(FileContext.class);
    public static String primaryId(String prefix){

        return new StringBuilder(prefix)
                .append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")))
                .append(RandomUtil.randomStr(14)).toString();

    }

    public static String getFileNameSuffix(String fileName) {

        if (fileName.indexOf(".") == -1) {
            return "";
        }

        String suffix = fileName.substring(fileName.lastIndexOf("."));
        return suffix;
    }

    /**
     * 创建目录
     *
     * @param destDirName
     *            目标目录名
     * @return 目录创建成功返回true，否则返回false
     */
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        // 创建单个目录
        if (dir.mkdirs()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除文件
     *
     * @param filePathAndName
     *            String 文件路径及名称 如c:/fqf.txt
     */
    public static void delFile(String filePathAndName) {
        try {
            String filePath = filePathAndName;
            filePath = filePath.toString();
            File myDelFile = new File(filePath);
            myDelFile.delete();
        } catch (Exception e) {
            System.out.println("删除文件操作出错");
            logger.error("删除文件操作出错", e);
        }
    }

    /**
     * 读取到字节数组0
     *
     * @param filePath
     *            //路径
     * @throws IOException
     */
    public static byte[] getContent(String filePath) throws IOException {
        File file = new File(filePath);
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            System.out.println("file too big...");
            return null;
        }
        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }
        // 确保所有数据均被读取
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }
        fi.close();
        return buffer;
    }

    /**
     * 读取到字节数组1
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray(String filePath) throws IOException {

        File f = new File(filePath);
        if (!f.exists()) {
            throw new FileNotFoundException(filePath);
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(f));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            logger.error("读取到字节数组1", e);
            throw e;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                logger.error("关闭流错误", e);
            }
            bos.close();
        }
    }

    /**
     * 读取到字节数组2
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray2(String filePath) throws IOException {
        File f = new File(filePath);
        if (!f.exists()) {
            throw new FileNotFoundException(filePath);
        }
        FileChannel channel = null;
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(f);
            channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while ((channel.read(byteBuffer)) > 0) {
                // do nothing
                // System.out.println("reading");
            }
            return byteBuffer.array();
        } catch (IOException e) {
            logger.error("读取到字节数组2", e);
            throw e;
        } finally {
            try {
                channel.close();
            } catch (IOException e) {
                logger.error("关闭流错误", e);
            }
            try {
                fs.close();
            } catch (IOException e) {
                logger.error("关闭流错误", e);
            }
        }
    }

    /**
     * Mapped File way MappedByteBuffer 可以在处理大文件时，提升性能
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray3(String filePath) throws IOException {

        FileChannel fc = null;
        RandomAccessFile rf = null;
        try {
            rf = new RandomAccessFile(filePath, "r");
            fc = rf.getChannel();
            MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()).load();
            // System.out.println(byteBuffer.isLoaded());
            byte[] result = new byte[(int) fc.size()];
            if (byteBuffer.remaining() > 0) {
                // System.out.println("remain");
                byteBuffer.get(result, 0, byteBuffer.remaining());
            }
            return result;
        } catch (IOException e) {
            logger.error("映射文件方式MappedByteBuffer", e);
            throw e;
        } finally {
            try {
                rf.close();
                fc.close();
            } catch (IOException e) {
                logger.error("关闭流错误", e);
            }
        }
    }


    /**
     * @DateTime 2015年4月24日 上午11:17:32
     * @Author 刘兴密
     * @QQ 63972012
     * @Desc 写文件
     * @param in
     *            输入流
     * @param outFilePath
     *            输出文件路径 void
     */
    public static void writeFile(InputStream in, String outFilePath) throws Exception{

        OutputStream out = null;
        BufferedInputStream fis = null;
        BufferedOutputStream fos = null;
        try {

            fis = new BufferedInputStream(in);

            out = new FileOutputStream(outFilePath);
            fos = new BufferedOutputStream(out);

            byte[] b = new byte[8192];
            int length = 0;

            while ((length = fis.read(b)) != -1) {
                fos.write(b, 0, length);
            }

            fos.flush();

            fis.close();
            in.close();
            fos.close();
            out.close();

        } catch (Exception e) {
            try {
                fis.close();
                in.close();
                fos.close();
                out.close();
                logger.error("写文件关闭流出错", e);
            } catch (IOException e1) {
                logger.error("写文件关闭流出错", e);
            }
        }

    }
}
